package org.hq.web.service;
import org.hq.web.sql.pojo.WebUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;


/**
 * 自定义 Security UserDetails
 * 系统登录用户账号密码
 * 用于数据库读取账号密码跟
 * web 页面账号密码校验
 *
 */

public class UserDateilsServiceImpl implements UserDetailsService {
    /**
     * 模拟数据库对象
     */
    private static ConcurrentHashMap<String, WebUser> user = new ConcurrentHashMap<String, WebUser>();
    static {
        user.put("root",new WebUser("root","系统","1813033378","ddddghj"));
        user.put("he",new WebUser("he","系统","1813033378","ddddghj"));
        user.put("qq",new WebUser("qq", "何桥", "1813033378", "admin"));
        user.put("heqiao",new WebUser("heqiao","系统","1813033378","ddddghj"));
    }


    //密码

    private PasswordEncoder pw;
    @Override
    @Cacheable
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
       System.out.println("用户登录"+username);

        //判断用户是否存在
        if (!user.containsKey(username)) {
        throw new UsernameNotFoundException("用户不存在"+username);
       }
        this.pw = new BCryptPasswordEncoder();
        //密码加密
        String password = pw.encode(user.get(username).getPassword());
        //用户配置
        List<GrantedAuthority> Authorities = AuthorityUtils.commaSeparatedStringToAuthorityList(user.get(username).getGranted());
      User users=  new User(username,password,Authorities);
        return users;
    }
}
